package com.lmb.util;

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import java.util.Properties;

public class EmailUtil {
    private static final String FROM = "1810679194@qq.com";// 发件人
    private static final String AUTH_CODE = "shcxjcaosctlchif";// 授权码
    private static final String HOST = "smtp.qq.com";// 发件服务器
    public static final String PORT = "465";// 端口

    private static final Session session;

    static {
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", HOST);
        props.setProperty("mail.smtp.port", PORT);
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.ssl.enable", "true");

        session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM, AUTH_CODE);
            }
        });

        // 生产环境建议关闭Debug模式，避免额外日志干扰
        session.setDebug(false);
    }

    public static void sendEmail(String to, String text) {
        Message message = new MimeMessage(session);
        Transport transport = null;
        try {
            message.setFrom(new InternetAddress(FROM));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("利民宝密码重置邮件");
            message.setContent("<h1 style='color:red'>验证码:" + text + "</h1>", "text/html;charset=utf-8");

            // 显式获取Transport并发送，避免自动关闭可能的重复操作
            transport = session.getTransport("smtp");
            transport.connect(HOST, FROM, AUTH_CODE);
            transport.sendMessage(message, message.getAllRecipients());
            System.out.println("邮件发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("邮件发送失败：" + e.getMessage());
        } finally {
            // 确保Transport仅关闭一次
            if (transport != null && transport.isConnected()) {
                try {
                    transport.close(); // 关闭连接（发送QUIT命令）
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}